package com.xdf.ecommerce.utils;


import com.alibaba.fastjson.JSON;
import com.xdf.ecommerce.constant.CommonConstant;
import com.xdf.ecommerce.vo.LoginUserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import sun.misc.BASE64Decoder;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Calendar;

/**
 * @author chanchaw
 * @create 2025-10-16 9:09
 */
public class TokenUtils {
    public static LoginUserInfo getUserInfo(String tokenStr) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        if(tokenStr == null) return null;
        Jws<Claims> claimsJws = parseToken(tokenStr,getPublicKey());
        Claims body = claimsJws.getBody();
        if(body.getExpiration().before(Calendar.getInstance().getTime())) return null;// token过期
        return JSON.parseObject(body.get(CommonConstant.JWT_USER_INFO_KEY).toString(),LoginUserInfo.class);
    }

    private static Jws<Claims> parseToken(String token,PublicKey publicKey){
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }
    private static PublicKey getPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
                new BASE64Decoder().decodeBuffer(CommonConstant.RSA_PUBLIC_KEY)
        );
        return KeyFactory.getInstance("RSA").generatePublic(keySpec);
    }
}
